<template>
	<view class="container">
		<scroll-view class="tabs-scroll" scroll-x="true" show-scrollbar="false">
			<view class="tabs">
				<view 
					class="tab-item" 
					v-for="(tab, index) in tabs" 
					:key="index" 
					:class="{ 'active': activeTab === tab.value }"
					@click="handleTabChange(tab.value)"
				>
					<text>{{ tab.label }}</text>
				</view>
			</view>
		</scroll-view>
		
		<view v-if="loading" class="loading">
			<image src="/static/icons/loading.gif" mode="aspectFit" class="loading-icon"></image>
			<text>加载中...</text>
		</view>
		
		<view v-else-if="showEmpty" class="empty">
			<image src="/static/icons/empty-order.png" mode="aspectFit" class="empty-icon"></image>
			<text>暂无订单数据</text>
		</view>
		
		<scroll-view v-else class="order-list" scroll-y="true" @scrolltolower="loadMore" refresher-enabled="true" :refresher-triggered="refreshing" @refresherrefresh="onRefresh" lower-threshold="100">
			<view v-for="order in orderList" :key="order.id" class="order-item">
				<view class="order-header">
					<view class="order-info">
						<text class="order-number">订单号：{{ order.orderNo }}</text>
						<text class="order-date">下单时间：{{ formatDate(order.createTime) }}</text>
					</view>
					<view class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</view>
				</view>
				
				<view class="order-products">
					<view v-for="(item, index) in order.orderItems" :key="index" class="product-item" @click="viewOrderDetail(order)">
						<image 
							:src="getImgUrl(item.image && item.image.length > 0 ? item.image[0] : '')" 
							class="product-image"
							mode="aspectFill"
						></image>
						<view class="product-info">
							<text class="product-name">{{ item.commodityName }}</text>
							<view class="product-price-qty">
								<text class="product-price">¥{{ item.commodityPrice }}</text>
								<text class="product-qty">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="order-footer">
					<view class="order-total">
						<text>共{{ getTotalQuantity(order) }}件商品</text>
						<text>实付：<text class="price">¥{{ order.actualAmount || order.totalAmount }}</text></text>
					</view>
					<view class="order-actions">
						<button 
							v-if="order.status === 'PENDING_PAYMENT'" 
							class="action-btn primary"
							@click.stop="payOrder(order.orderNo)"
						>去付款</button>
						
						<button 
							v-if="order.status === 'SHIPPED'" 
							class="action-btn primary"
							@click.stop="completeOrder(order)"
						>确认收货</button>
						
						<button 
							v-if="order.status === 'PENDING_PAYMENT'" 
							class="action-btn"
							@click.stop="cancelOrder(order)"
						>取消订单</button>
						
						<button 
							class="action-btn"
							@click.stop="viewOrderDetail(order)"
						>查看详情</button>
					</view>
				</view>
			</view>
			
			<view v-if="loadingMore" class="loading-more">
				<text>加载更多...</text>
			</view>
			
			<view v-if="noMoreData && orderList.length > 0" class="no-more">
				<text>没有更多数据了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { SERVER_BASE_URL } from '@/utils/request';
import http from '@/utils/request';

export default {
	data() {
		return {
			orderList: [],
			loading: false,
			loadingMore: false,
			refreshing: false,
			showEmpty: false,
			noMoreData: false,
			userId: null,
			activeTab: 'all',
			currentPage: 1,
			pageSize: 10,
			serverBaseUrl: SERVER_BASE_URL,
			tabs: [
				{ label: '全部', value: 'all' },
				{ label: '待付款', value: 'pending-payment' },
				{ label: '待发货', value: 'paid' },
				{ label: '待收货', value: 'shipped' },
				{ label: '已完成', value: 'completed' },
				{ label: '已取消', value: 'cancelled' }
			]
		};
	},
	onLoad(options) {
		this.checkLoginStatus();
		
		// 如果有传入状态参数，则切换到对应标签
		if (options.status) {
			switch (options.status) {
				case 'PENDING_PAYMENT':
					this.activeTab = 'pending-payment';
					break;
				case 'PAID':
					this.activeTab = 'paid';
					break;
				case 'SHIPPED':
					this.activeTab = 'shipped';
					break;
				case 'COMPLETED':
					this.activeTab = 'completed';
					break;
				case 'CANCELLED':
					this.activeTab = 'cancelled';
					break;
				default:
					this.activeTab = 'all';
			}
		}
	},
	onShow() {
		this.refreshOrderList();
	},
	// 启用下拉刷新
	onPullDownRefresh() {
		this.onRefresh();
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const userStr = uni.getStorageSync('user');
			if (userStr) {
				try {
					const userInfo = JSON.parse(userStr);
					if (userInfo && userInfo.id) {
						this.userId = userInfo.id;
						return true;
					}
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
			
			return false;
		},
		
		// 根据标签获取状态参数
		getStatusForTab(tab) {
			switch (tab) {
				case 'pending-payment':
					return 'PENDING_PAYMENT';
				case 'paid':
					return 'PAID';
				case 'shipped':
					return 'SHIPPED';
				case 'completed':
					return 'COMPLETED';
				case 'cancelled':
					return 'CANCELLED';
				default:
					return '';
			}
		},
		
		// 刷新订单列表（重置页码）
		refreshOrderList() {
			this.currentPage = 1;
			this.noMoreData = false;
			this.orderList = [];
			this.getOrderList(this.getStatusForTab(this.activeTab));
		},
		
		// 下拉刷新
		onRefresh() {
			this.refreshing = true;
			this.refreshOrderList();
		},
		
		// 加载更多
		loadMore() {
			if (this.loadingMore || this.noMoreData) return;
			this.currentPage++;
			this.getOrderList(this.getStatusForTab(this.activeTab), true);
		},
		
		// 获取订单列表
		async getOrderList(status = '', isLoadMore = false) {
			if (!this.checkLoginStatus()) return;
			
			if (isLoadMore) {
				this.loadingMore = true;
			} else {
				this.loading = true;
			}
			
			try {
				let params = {
					page: this.currentPage,
					size: this.pageSize
				};
				
				if (status) {
					params.status = status;
				}
				
				const response = await http.get('/order/list', { params });
				
				if (response.code === 200) {
					const newData = response.data || [];
					
					if (isLoadMore) {
						if (newData.length === 0) {
							this.noMoreData = true;
						} else {
							this.orderList = [...this.orderList, ...newData];
						}
					} else {
						this.orderList = newData;
						// 如果第一页没有满足pageSize，说明没有更多数据了
						if (newData.length < this.pageSize) {
							this.noMoreData = true;
						}
					}
					
					this.showEmpty = this.orderList.length === 0;
				} else {
					uni.showToast({
						title: response.message || '获取订单列表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取订单列表失败:', error);
				uni.showToast({
					title: '获取订单列表失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				this.loadingMore = false;
				this.refreshing = false;
				// 停止下拉刷新
				uni.stopPullDownRefresh();
			}
		},
		
		// 处理标签页切换
		handleTabChange(tab) {
			if (this.activeTab === tab) return;
			this.activeTab = tab;
			
			// 根据标签获取对应状态的订单
			this.refreshOrderList();
		},
		
		// 查看订单详情
		viewOrderDetail(order) {
			uni.navigateTo({
				url: `/pages/order/detail?orderNo=${order.orderNo}`
			});
		},
		
		// 取消订单
		cancelOrder(order) {
			if (!this.checkLoginStatus()) return;
			
			uni.showModal({
				title: '提示',
				content: '确定要取消该订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.put(`/order/cancel/${order.orderNo}`);
							
							if (response.code === 200) {
								uni.showToast({
									title: '订单取消成功',
									icon: 'success'
								});
								// 刷新当前标签页的订单列表
								this.refreshOrderList();
							} else {
								uni.showToast({
									title: response.message || '取消订单失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('取消订单失败:', error);
							uni.showToast({
								title: '取消订单失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 确认收货
		completeOrder(order) {
			if (!this.checkLoginStatus()) return;
			
			uni.showModal({
				title: '提示',
				content: '确认已收到商品？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.put(`/order/complete/${order.orderNo}`);
							
							if (response.code === 200) {
								uni.showToast({
									title: '确认收货成功',
									icon: 'success'
								});
								// 刷新当前标签页的订单列表
								this.refreshOrderList();
							} else {
								uni.showToast({
									title: response.message || '确认收货失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('确认收货失败:', error);
							uni.showToast({
								title: '确认收货失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 支付订单（跳转到订单详情页）
		payOrder(orderNo) {
			uni.navigateTo({
				url: `/pages/order/detail?orderNo=${orderNo}&pay=1`
			});
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '/static/icons/no-image.png';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			if (url.startsWith('/uploads/')) {
				fullUrl = this.serverBaseUrl + url;
			}
			
			return fullUrl;
		},
		
		// 格式化日期
		formatDate(dateString) {
			if (!dateString) return '-';
			const date = new Date(dateString);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},
		
		// 订单状态中文名称
		getStatusText(status) {
			const statusMap = {
				'PENDING_PAYMENT': '待付款',
				'PAID': '待发货',
				'SHIPPED': '待收货',
				'COMPLETED': '已完成',
				'CANCELLED': '已取消'
			};
			return statusMap[status] || status;
		},
		
		// 获取订单状态样式类名
		getStatusClass(status) {
			const classMap = {
				'PENDING_PAYMENT': 'pending',
				'PAID': 'paid',
				'SHIPPED': 'shipped',
				'COMPLETED': 'completed',
				'CANCELLED': 'cancelled'
			};
			return classMap[status] || '';
		},
		
		// 获取订单总数量
		getTotalQuantity(order) {
			if (!order || !order.orderItems) return 0;
			return order.orderItems.reduce((total, item) => total + (item.quantity || 0), 0);
		}
	}
};
</script>

<style>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 30rpx;
	display: flex;
	flex-direction: column;
}

.tabs-scroll {
	background-color: #fff;
	height: 80rpx;
	position: sticky;
	top: 0;
	z-index: 10;
}

.tabs {
	display: flex;
	padding: 0 20rpx;
	height: 80rpx;
	white-space: nowrap;
}

.tab-item {
	display: inline-flex;
	justify-content: center;
	align-items: center;
	font-size: 28rpx;
	color: #666;
	position: relative;
	min-width: 20%;
	height: 100%;
	padding: 0 20rpx;
}

.tab-item.active {
	color: #409EFF;
	font-weight: bold;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
	background-color: #409EFF;
}

.loading, .empty {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 30rpx;
}

.loading-icon, .empty-icon {
	width: 120rpx;
	height: 120rpx;
	margin-bottom: 20rpx;
}

.order-list {
	flex: 1;
	padding: 20rpx;
	height: calc(100vh - 80rpx);
}

.order-item {
	background-color: #fff;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.order-header {
	padding: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1rpx solid #eee;
}

.order-info {
	flex: 1;
}

.order-number {
	font-size: 26rpx;
	color: #333;
	margin-right: 20rpx;
}

.order-date {
	font-size: 24rpx;
	color: #999;
	display: block;
	margin-top: 10rpx;
}

.order-status {
	font-size: 28rpx;
	font-weight: bold;
}

.order-status.pending {
	color: #E6A23C;
}

.order-status.paid {
	color: #409EFF;
}

.order-status.shipped {
	color: #409EFF;
}

.order-status.completed {
	color: #67C23A;
}

.order-status.cancelled {
	color: #909399;
}

.order-products {
	padding: 20rpx;
}

.product-item {
	display: flex;
	padding: 10rpx 0;
	border-bottom: 1rpx dashed #f5f5f5;
}

.product-item:last-child {
	border-bottom: none;
}

.product-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 8rpx;
	background-color: #f5f5f5;
}

.product-info {
	flex: 1;
	margin-left: 20rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 26rpx;
	color: #333;
	line-height: 1.4;
	margin-bottom: 10rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.product-price-qty {
	display: flex;
	justify-content: space-between;
}

.product-price {
	font-size: 28rpx;
	color: #F56C6C;
	font-weight: bold;
}

.product-qty {
	font-size: 24rpx;
	color: #999;
}

.order-footer {
	padding: 20rpx;
	border-top: 1rpx solid #eee;
}

.order-total {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin-bottom: 20rpx;
}

.order-total text {
	font-size: 24rpx;
	color: #666;
	margin-left: 20rpx;
}

.order-total .price {
	color: #F56C6C;
	font-size: 30rpx;
	font-weight: bold;
}

.order-actions {
	display: flex;
	justify-content: flex-end;
	flex-wrap: wrap;
}

.action-btn {
	margin-left: 20rpx;
	margin-bottom: 10rpx;
	font-size: 24rpx;
	padding: 0 30rpx;
	height: 60rpx;
	line-height: 60rpx;
	background-color: #fff;
	border: 1rpx solid #ddd;
	border-radius: 30rpx;
	color: #666;
}

.action-btn.primary {
	background-color: #409EFF;
	color: #fff;
	border: none;
}

.loading-more, .no-more {
	text-align: center;
	padding: 20rpx 0;
	font-size: 24rpx;
	color: #999;
}
</style>